package com.sunlands.zlcx.usercenter.controller;

import com.sunlands.zlcx.usercenter.common.annotation.AutoLog;
import com.sunlands.zlcx.usercenter.common.cache.RedisDistributedLockImpl;
import com.sunlands.zlcx.usercenter.domain.share.UserShareCardDO;
import com.sunlands.zlcx.usercenter.domain.share.UserShareInfoDO;
import com.sunlands.zlcx.usercenter.domain.share.UserShareZanDO;
import com.sunlands.zlcx.usercenter.exception.CheckRunException;
import com.sunlands.zlcx.usercenter.exception.GlobalExceptionHandler;
import com.sunlands.zlcx.usercenter.service.UsersServiceImpl;
import com.sunlands.zlcx.usercenter.service.UsersShareServiceImpl;
import com.sunlands.zlcx.usercenter.util.AsyncTaskManager;
import com.sunlands.zlcx.usercenter.util.StringUtil;
import com.sunlands.zlcx.usercenter.vo.*;
import com.sunlands.zlcx.usercenter.vo.response.BusinessResult;
import com.sunlands.zlcx.usercenter.vo.share.UserShareCardVO;
import com.sunlands.zlcx.usercenter.vo.share.UserShareInfoVO;
import com.sunlands.zlcx.usercenter.vo.share.UserShareZanVO;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;

import static com.sunlands.zlcx.usercenter.common.annotation.AutoLog.Level.DEBUG;

/**
 * @author 郜炎峰
 * description: 用户分享
 */
@SuppressWarnings("unused")
@Api(tags = "4、用户分享", position = 4)
@ApiResponses(value = {@ApiResponse(code = 400, response = GlobalExceptionHandler.class, message = "数据校验失败"), @ApiResponse(code = 500, response = GlobalExceptionHandler.class, message = "内部错误")})
@Slf4j
@RestController
@RequestMapping("/share")
public class UsersShareController implements AuthSupport {

    @ApiOperation(value = "学习计时点赞", notes = "学习计时点赞")
    @PostMapping("/add/zan")
    @AutoLog
//    @PreAuthorize("isAuthenticated()")
//    @AuthSig
    public BusinessResult addZan(@ApiParam(required = true, value = "用户学习计时点赞")@RequestBody UserShareZanDO userShareZanDO){
        String checkAddZan = checkAddZan(userShareZanDO);
        if (null != checkAddZan){
            return BusinessResult.createInstance(CommonResultMessage.PARAMS_NOT_INVALIDE, checkAddZan);
        }
        try{
            if (redisDistributedLock.openUserLock(userShareZanDO.getZanUserId())) {
                UserShareInfoDO shareInfoDO = usersShareService.getShareInfoByLearnId(userShareZanDO.getLearnId());
                if (null == shareInfoDO) {
                    return BusinessResult.createInstance(CommonResultMessage.PARAMS_NOT_NULL, "");
                }
                userShareZanDO.setShareId(shareInfoDO.getId());
                userShareZanDO.setShareUserId(shareInfoDO.getUserId());
                userShareZanDO.setZanUserId(userShareZanDO.getZanUserId());
                UserShareZanVO userShareZanVO = usersShareService.addZan(userShareZanDO);
                return BusinessResult.createSuccessInstance(userShareZanVO);
            }
        }catch (CheckRunException ex){
            log.info(" user add share zan error , ex = {}",ex);
            return BusinessResult.createInstance(CommonResultMessage.UNKOWN_ERROR.code,ex.getMessage(), ex.getMessage());
        }catch (Exception ex){
            log.info(" user add share zan error , ex = {}",ex);
        } finally {
            redisDistributedLock.releaseUserLock(userShareZanDO.getZanUserId());
        }
        return BusinessResult.createInstance(CommonResultMessage.UNKOWN_ERROR);
    }

    @ApiOperation(value = "学习计时打卡", notes = "学习计时打卡")
    @PostMapping("/add/card")
    @AutoLog
//    @PreAuthorize("isAuthenticated()")
//    @AuthSig
    public BusinessResult addCard(@ApiParam(required = true, value = "用户学习计时打卡")@RequestBody UserShareCardDO userShareCardDO){
        String checkAddCard = checkAddCard(userShareCardDO);
        if (null != checkAddCard){
            return BusinessResult.createInstance(CommonResultMessage.PARAMS_NOT_INVALIDE, checkAddCard);
        }
        try{
            if (redisDistributedLock.openUserLock(userShareCardDO.getCardUserId())) {
                UserShareInfoDO shareInfoDO = usersShareService.getShareInfoByLearnId(userShareCardDO.getLearnId());
                if (null == shareInfoDO) {
                    return BusinessResult.createInstance(CommonResultMessage.PARAMS_NOT_NULL, "分享不存在");
                }
                userShareCardDO.setShareId(shareInfoDO.getId());
                userShareCardDO.setShareUserId(shareInfoDO.getUserId());
                userShareCardDO.setCardUserId(userShareCardDO.getCardUserId());
                UserShareCardVO userShareCardVO = usersShareService.addCard(userShareCardDO);
                return BusinessResult.createSuccessInstance(userShareCardVO);
            }
        }catch (CheckRunException ex){
            log.info(" user add share card error , ex = {}",ex);
            return BusinessResult.createInstance(CommonResultMessage.UNKOWN_ERROR.code,ex.getMessage(), ex.getMessage());
        }catch (Exception ex){
            log.info(" user add share card error , ex = {}",ex);
        } finally {
            redisDistributedLock.releaseUserLock(userShareCardDO.getCardUserId());
        }
        return BusinessResult.createInstance(CommonResultMessage.UNKOWN_ERROR);
    }


    @ApiOperation(value = "用户分享学习计时", notes = "用户分享学习计时")
    @PostMapping("/add")
    @AutoLog
//    @PreAuthorize("isAuthenticated()")
//    @AuthSig
    public BusinessResult addShare(@ApiParam(required = true, value = "用户学习VO")@RequestBody UserShareInfoDO userShareInfoDO){
        Long userId = currentUserId();
        String checkAddShare = checkAddShare(userShareInfoDO);
        if (null != checkAddShare){
            return BusinessResult.createInstance(CommonResultMessage.PARAMS_NOT_INVALIDE, checkAddShare);
        }
        try{
            if (redisDistributedLock.openUserLock(userId)) {
                userShareInfoDO.setUserId(userId);
                usersShareService.add(userShareInfoDO);
                return BusinessResult.createSuccessInstance(null);
            }
        }catch (Exception ex){
            log.info(" user add share error , ex = {}",ex);
        } finally {
            redisDistributedLock.releaseUserLock(userId);
        }
        return BusinessResult.createInstance(CommonResultMessage.UNKOWN_ERROR, "未知错误，请联系管理员");
    }

    @ApiOperation(value = "获取用户分享学习计时", notes = "获取用户分享学习计时", response = UserShareInfoVO.class)
    @GetMapping("/get")
    @AutoLog(logLevel = DEBUG)
//    @PreAuthorize("isAuthenticated()")
//    @AuthSig
    public BusinessResult getShareByLearnId(@ApiParam(required = true, value = "用户id")@RequestParam Long userId,
                                            @ApiParam(required = true, value = "学习计时id")@RequestParam Long learnId){
        try{
            UsersVO usersVO = usersService.find(userId);
            if (null == usersVO) {
                return BusinessResult.createInstance(CommonResultMessage.INVALID_USER);
            }
            UserShareInfoVO shareInfoVO = usersShareService.getShareInfo(learnId, userId);
            return BusinessResult.createSuccessInstance(shareInfoVO);
        }catch (Exception ex){
            log.info(" user get share error , ex = {}",ex);
        }
        return BusinessResult.createInstance(CommonResultMessage.UNKOWN_ERROR, "未知错误，请联系管理员");
    }

    private String checkAddShare(UserShareInfoDO userShareInfoDO) {
        if (userShareInfoDO.getLearnId() == null) {
            return "学习计时id为空";
        }
        return null;
    }

    private String checkAddZan(UserShareZanDO userShareZanDO) {
        if (userShareZanDO.getLearnId() == null) {
            return "学习计时的id不能为空";
        } else if (userShareZanDO.getZanUserId() == null) {
            return "用户id不能为空";
        }
        return null;
    }
    private String checkAddCard(UserShareCardDO userShareCardDO) {
        if (userShareCardDO.getLearnId() == null) {
            return "学习计时的id不能为空";
        } else if (StringUtil.isEmpty(userShareCardDO.getCardContent())) {
            userShareCardDO.setCardContent("参与学习打卡");
        } else if (userShareCardDO.getCardUserId() == null) {
            return "用户id不能为空";
        }
        return null;
    }


    @Autowired
    @Lazy
    private UsersShareServiceImpl usersShareService;
    @Autowired
    @Lazy
    private UsersServiceImpl usersService;
    @Autowired
    private RedisDistributedLockImpl redisDistributedLock;
    @Autowired
    private AsyncTaskManager asyncTaskManager;
}
